//
//  GameModel.m
//  Mahjong
//
//  Created by 饶首建 on 17/5/22.
//  Copyright © 2017年 com.ikamobile.com. All rights reserved.
//

#import "GameModel.h"
#import "ResultModel.h"
#import "ActionModel.h"

@implementation GameModel

+(void)gamesOfMatch:(NSString *)matchId success:(LoadGamesSuccess)success fail:(LoadGamesFail)fail{
    NSString *url = [BASE_URL stringByAppendingPathComponent:NSStringFormat(@"Matches/%@/games",matchId)];
    [HttpUtil sendRequestURL:url method:GET param:nil success:^(id response) {
        NSMutableArray *arr = [NSMutableArray new];
        NSDictionary *dic = response;
        for (NSDictionary *d in dic) {
            GameModel *gm = [GameModel gameModelPushParse:d];
            [arr addObject:gm];
        }
        success(arr);
    } fail:^(NSString *errorStr) {
        fail(errorStr);
    }];
}

+(GameModel *)gameModelPushParse:(NSDictionary*)dic{
    //    JSONString = @"{\"results\":[{\"id\":\"35176a6a-cc58-4254-80df-23dc56ada591\",\"name\":\"你自己\",\"score\":-1},{\"id\":\"8d445a06-4617-4be9-9c1e-ccfbd96d9b96\",\"name\":\"玩家B\",\"score\":-2},{\"id\":\"24b62c74-242c-483c-9846-966db99ef481\",\"name\":\"玩家C\",\"score\":1},{\"id\":\"ab13563f-491d-4384-a927-da6c60df84dd\",\"name\":\"玩家D\",\"score\":2}],\"id\":\"5925466604f6e72af6dcafeb\",\"matchId\":\"5925466504f6e72af6dcafea\",\"_actions\":[{\"id\":\"4df5c210-405c-11e7-b21d-f1616e56b806\",\"type\":\"胡\",\"attributes\":[\"杠上花\",\"自摸\"],\"owner\":{\"id\":\"35176a6a-cc58-4254-80df-23dc56ada591\",\"name\":\"你自己\"},\"targets\":[{\"id\":\"24b62c74-242c-483c-9846-966db99ef481\",\"name\":\"玩家C\"},{\"id\":\"ab13563f-491d-4384-a927-da6c60df84dd\",\"name\":\"玩家D\"}]}]}";
    //    NSDictionary *dic = [self dictionaryWithJsonString:JSONString];
    GameModel *gm = [GameModel new];
    gm.gameId = dic[@"id"];
    gm.matchId = dic[@"matchId"];
    
    NSDictionary *resultDic = dic[@"results"];
    NSMutableArray *resultArr = [NSMutableArray new];
    for (NSDictionary *d in resultDic) {
        ResultModel *rm = [ResultModel new];
        PlayerModel *pm = [PlayerModel parse:d];
        rm.playerModel = pm;
        rm.score = [d[@"score"] integerValue];
        [resultArr addObject:rm];
    }
    gm.resultArr = resultArr;
    
    NSDictionary *actionDic = dic[@"_actions"];
    NSMutableArray *actionArr = [NSMutableArray new];
    for (NSDictionary *d in actionDic) {
        ActionModel *am = [ActionModel parseDic:d];
        [actionArr addObject:am];
    }
    gm.actionArr = actionArr;
    return gm;
}


+(GameModel *)gameModelNewParse:(NSDictionary *)dic{
    GameModel *gm = [GameModel new];
    gm.gameId = dic[@"id"];
    NSMutableArray *tmpArr = [NSMutableArray new];
    for (NSDictionary *d in dic[@"results"]) {
        ResultModel *rm = [ResultModel new];
        PlayerModel *pm = [PlayerModel parse:d];
        rm.playerModel = pm;
        rm.score = [d[@"score"] integerValue];
        [tmpArr addObject:rm];
    }
    gm.resultArr = tmpArr;
    return gm;
}

@end
